﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cn.Cellula.Model.Security;
using Cn.Edwon.Web.Session;
using Cn.Cellula.Biz.Port;
using Cn.Edwon.Spring;
using Cn.Edwon.Web.Ac;
using Cn.Cellula.Biz;
using Cn.Edwon.Web;

namespace Cn.Cellula.Client {
    public class LoginHelper {
        IUserBiz biz = BizFactory.Get<IUserBiz>();
        public LoginHelper() { 
        }
        public void Login(String rLoginNameProperty, string rLoginName, string rMd5Pwd, ref ISessActor rActor) {
            VSysUserEO user = biz.Login(rLoginNameProperty,rLoginName,rMd5Pwd);
            BindLoginData(user, ref rActor);
        }
        public void Login(String rUserKey, String rMd5Pwd, ref ISessActor rActor) {
            VSysUserEO user = biz.Login(rUserKey, rMd5Pwd);
            BindLoginData(user, ref rActor);
        }

        public void BindLoginData(VSysUserEO eo, ref ISessActor rActor) {
            if (eo == null) {
                rActor = null;
                return;
            }
            rActor.Email = eo.Email;
            rActor.ID = eo.UserKey;
            rActor.LastDate = DateTime.Now;
            rActor.LoginName = eo.LoginName;
            rActor.OwnerKey = eo.OwnerKey;
            rActor.Password = eo.Password;
            rActor.Src = eo;
            rActor.UserName = eo.UserName;
            rActor.ActivateCode = eo.ActivateCode;
            rActor.ActivatedFlg = (eo.ActivatedFlg==null)?0:Convert.ToInt32(eo.ActivatedFlg);
            rActor.Power = new UserPower();
            rActor.Power.RoleKey = eo.RoleKey;
            rActor.Power.RoleName = eo.RoleName;
            rActor.Power.IsSysop = (eo.IsSysop == 1);
            rActor.Power.DeptKey = eo.DeptKey;
            rActor.Power.DeptName = eo.DeptName;
            if (eo.UserKey == BizConst.Admin.KEY) {
                rActor.Power.IsSysop = true;
                rActor.Power.RoleLevel = 9999999;
                rActor.Power.DeptLevel = 9999999;
            } else {
                rActor.Power.IsSysop = (eo.IsSysop == 1);
                rActor.Power.RoleLevel = (eo.RoleLevel == null) ? 0 : eo.RoleLevel;
                rActor.Power.DeptLevel = (eo.DeptLevel == null) ? 0 : eo.DeptLevel;
            }
            rActor.SecurityUrls = new List<String>();
            IList<VUserFunctionEO> list = biz.LoadFuncByUser(eo.UserKey);
            if (list != null && list.Count > 0) {
                foreach (VUserFunctionEO f in list) {
                    rActor.SecurityUrls.Add(ClientHelper.RootUrl + f.MarkPattern);
                }
            }
        }
    }
}
